// @ts-ignore
import { ref, computed } from 'vue'
// @ts-ignore
import { defineStore } from 'pinia'
// @ts-ignore
import { useRouter } from 'vue-router'

interface User {
    id: number
    username: string
    email?: string
    avatar?: string
    password?: string // 添加密码字段用于验证
}

// 密码修改请求接口
interface ChangePasswordRequest {
    oldPassword: string
    newPassword: string
    confirmPassword: string
}

export const useUserStore = defineStore('user', () => {
    const router = useRouter()

    // 状态 - 从 localStorage 初始化
    const currentUser = ref<User | null>(
        localStorage.getItem('currentUser')
            ? JSON.parse(localStorage.getItem('currentUser')!)
            : null
    )

    const token = ref(localStorage.getItem('token') || '')
    const isLoggedIn = computed(() => !!token.value)

    // 模拟用户数据库（存储在 localStorage 中）
    const getRegisteredUsers = (): User[] => {
        const users = localStorage.getItem('registeredUsers')
        return users ? JSON.parse(users) : [
            {
                id: 1,
                username: 'admin',
                password: '123456', // 存储密码用于验证
                email: 'admin@easygo.com',
                avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
            }
        ]
    }

    const saveRegisteredUsers = (users: User[]): void => {
        localStorage.setItem('registeredUsers', JSON.stringify(users))
    }

    // 注册功能
    const register = async (username: string, password: string, email?: string): Promise<void> => {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                // 表单验证
                if (!username || !password) {
                    reject(new Error('用户名和密码不能为空'))
                    return
                }

                if (username.length < 3) {
                    reject(new Error('用户名至少3位字符'))
                    return
                }

                if (password.length < 6) {
                    reject(new Error('密码至少6位字符'))
                    return
                }

                const registeredUsers = getRegisteredUsers()

                // 检查用户名是否已存在
                const existingUser = registeredUsers.find(user => user.username === username)
                if (existingUser) {
                    reject(new Error('用户名已存在'))
                    return
                }

                // 创建新用户
                const newUser: User = {
                    id: Date.now(), // 使用时间戳作为唯一ID
                    username,
                    password, // 存储密码用于登录验证
                    email: email || '',
                    avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
                }

                // 保存到注册用户列表
                registeredUsers.push(newUser)
                saveRegisteredUsers(registeredUsers)

                // 注册成功后自动登录
                currentUser.value = {
                    id: newUser.id,
                    username: newUser.username,
                    email: newUser.email,
                    avatar: newUser.avatar
                }
                token.value = `user-token-${newUser.id}`

                // 持久化到 localStorage
                localStorage.setItem('currentUser', JSON.stringify(currentUser.value))
                localStorage.setItem('token', token.value)

                resolve()
            }, 500)
        })
    }

    // 登录功能（修改为支持注册用户登录）
    const login = async (username: string, password: string): Promise<void> => {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                const registeredUsers = getRegisteredUsers()
                const user = registeredUsers.find(u => u.username === username && u.password === password)

                if (user) {
                    // 登录成功
                    currentUser.value = {
                        id: user.id,
                        username: user.username,
                        email: user.email,
                        avatar: user.avatar
                    }
                    token.value = user.username === 'admin' ? 'admin-demo-token' : `user-token-${user.id}`

                    // 持久化到 localStorage
                    localStorage.setItem('currentUser', JSON.stringify(currentUser.value))
                    localStorage.setItem('token', token.value)

                    resolve()
                } else {
                    reject(new Error('用户名或密码错误'))
                }
            }, 500)
        })
    }

    // 退出登录
    const logout = (): void => {
        currentUser.value = null
        token.value = ''
        localStorage.removeItem('currentUser')
        localStorage.removeItem('token')

        // 退出后跳转到登录页
        router.push('/')
    }

    // 获取所有注册用户（用于管理）
    const getUsers = (): User[] => {
        return getRegisteredUsers().map(user => ({
            id: user.id,
            username: user.username,
            email: user.email,
            avatar: user.avatar
            // 不返回密码字段
        }))
    }

    // ========== 新增个人中心相关功能 ==========

    // 更新用户信息
    const updateUserInfo = async (userData: Partial<User>): Promise<void> => {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                if (!currentUser.value) {
                    reject(new Error('用户未登录'))
                    return
                }

                try {
                    // 更新当前用户信息
                    currentUser.value = { ...currentUser.value, ...userData }

                    // 更新 localStorage
                    localStorage.setItem('currentUser', JSON.stringify(currentUser.value))

                    // 同时更新注册用户列表中的信息
                    const registeredUsers = getRegisteredUsers()
                    const userIndex = registeredUsers.findIndex(u => u.id === currentUser.value!.id)
                    if (userIndex !== -1) {
                        // 保留密码字段，不更新密码
                        const updatedUser = {
                            ...registeredUsers[userIndex],
                            ...userData
                        }
                        registeredUsers[userIndex] = updatedUser
                        saveRegisteredUsers(registeredUsers)
                    }

                    resolve()
                } catch (error) {
                    reject(new Error('更新用户信息失败'))
                }
            }, 500)
        })
    }

    // 修改密码
    const changePassword = async (passwordData: ChangePasswordRequest): Promise<void> => {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                if (!currentUser.value) {
                    reject(new Error('用户未登录'))
                    return
                }

                // 验证输入
                if (!passwordData.oldPassword || !passwordData.newPassword || !passwordData.confirmPassword) {
                    reject(new Error('请填写完整信息'))
                    return
                }

                if (passwordData.newPassword !== passwordData.confirmPassword) {
                    reject(new Error('两次输入的新密码不一致'))
                    return
                }

                if (passwordData.newPassword.length < 6) {
                    reject(new Error('新密码长度不能少于6位'))
                    return
                }

                const registeredUsers = getRegisteredUsers()
                const userIndex = registeredUsers.findIndex(u => u.id === currentUser.value!.id)

                if (userIndex === -1) {
                    reject(new Error('用户不存在'))
                    return
                }

                // 验证原密码
                if (registeredUsers[userIndex].password !== passwordData.oldPassword) {
                    reject(new Error('原密码错误'))
                    return
                }

                try {
                    // 更新密码
                    registeredUsers[userIndex].password = passwordData.newPassword
                    saveRegisteredUsers(registeredUsers)

                    resolve()
                } catch (error) {
                    reject(new Error('修改密码失败'))
                }
            }, 500)
        })
    }

    // 上传头像
    const uploadAvatar = async (file: File): Promise<string> => {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                if (!currentUser.value) {
                    reject(new Error('用户未登录'))
                    return
                }

                try {
                    // 创建文件读取器
                    const reader = new FileReader()
                    reader.onload = (e) => {
                        const avatarUrl = e.target?.result as string

                        // 更新用户头像
                        currentUser.value!.avatar = avatarUrl
                        localStorage.setItem('currentUser', JSON.stringify(currentUser.value))

                        // 同时更新注册用户列表
                        const registeredUsers = getRegisteredUsers()
                        const userIndex = registeredUsers.findIndex(u => u.id === currentUser.value!.id)
                        if (userIndex !== -1) {
                            registeredUsers[userIndex].avatar = avatarUrl
                            saveRegisteredUsers(registeredUsers)
                        }

                        resolve(avatarUrl)
                    }
                    reader.onerror = () => reject(new Error('文件读取失败'))
                    reader.readAsDataURL(file)
                } catch (error) {
                    reject(new Error('头像上传失败'))
                }
            }, 500)
        })
    }

    // 获取当前用户完整信息（包含密码字段，仅用于验证）
    const getCurrentUserWithPassword = (): User | null => {
        if (!currentUser.value) return null

        const registeredUsers = getRegisteredUsers()
        return registeredUsers.find(u => u.id === currentUser.value!.id) || null
    }

    // 初始化 - 仅从 localStorage 恢复，不设置默认值
    const init = (): void => {
        const savedToken = localStorage.getItem('token')
        const savedUser = localStorage.getItem('currentUser')

        if (savedToken && savedUser) {
            token.value = savedToken
            currentUser.value = JSON.parse(savedUser)
        }
    }

    // 立即初始化
    init()

    return {
        currentUser,
        token,
        isLoggedIn,
        register,
        login,
        logout,
        getUsers,
        init,
        // 新增的个人中心功能
        updateUserInfo,
        changePassword,
        uploadAvatar,
        getCurrentUserWithPassword
    }
})